package com.jz.community.basecomm.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.jz.community.basecomm.base.BaseSP;
import com.jz.community.basecomm.bean.BaseCommLocateInfo;
import com.jz.community.basecomm.bean.LoginBaseInfo;
import com.jz.community.basecomm.bean.RegionsBean;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Tony.Fan on 2018/3/20 17:41
 */
public class BaseSpUtils extends BaseSP {

    public static String FILE_NAME = "community_base_user_msg";

    private static BaseSpUtils spUtils = new BaseSpUtils();

    public static BaseSpUtils getInstance() {
        return spUtils;
    }

    @Override
    public String getModelPreferenceFIleName() {
        return FILE_NAME;
    }


    public void setCurrentCommuity(Context context, BaseCommLocateInfo baseCommLocateInfo) {
        String jsonData = "";
        if (baseCommLocateInfo != null) {
            jsonData = JSON.toJSONString(baseCommLocateInfo);
        }
        putString(context, "current_commuity", jsonData);
    }

    public BaseCommLocateInfo getCurrentCommuity(Context context) {
        String jsonData = getString(context, "current_commuity");
        if (!Preconditions.isNullOrEmpty(jsonData)) {
            return JsonUtils.parseObject(jsonData, BaseCommLocateInfo.class);
        } else {
            BaseCommLocateInfo baseCommLocateInfo = new BaseCommLocateInfo("西安市", "txsm", 0, "108.94702", "34.259432", "34.259432", "108.94702", "陕西省", "", "西安市", "029", "", "", "", "");
            return baseCommLocateInfo;
        }

    }

    public void setRegion(Context context, RegionsBean.EmbeddedBean.ContentBean bean) {
        String jsonData = "";
        if (bean != null) {
            jsonData = JSON.toJSONString(bean);
        }
        putString(context, "region", jsonData);
    }

    public RegionsBean.EmbeddedBean.ContentBean getRegion(Context context) {
        String jsonData = getString(context, "region");
        if (!Preconditions.isNullOrEmpty(jsonData)) {
            return JsonUtils.parseObject(jsonData, RegionsBean.EmbeddedBean.ContentBean.class);
        } else {
            return getRegionList(context).get_embedded().getContent().get(0);
        }

    }

    public void setRegionList(Context context, RegionsBean regionsBean) {
        String jsonData = "";
        if (regionsBean != null) {
            jsonData = JSON.toJSONString(regionsBean);
        }
        putString(context, "regionList", jsonData);
    }

    public RegionsBean getRegionList(Context context) {
        String jsonData = getString(context, "regionList");
        if (!Preconditions.isNullOrEmpty(jsonData)) {
            return JsonUtils.parseObject(jsonData, RegionsBean.class);
        } else {
            RegionsBean regionsBean = new RegionsBean();
            RegionsBean.EmbeddedBean embeddedBean = new RegionsBean.EmbeddedBean();
            RegionsBean.EmbeddedBean.ContentBean contentBean = new RegionsBean.EmbeddedBean.ContentBean();
            contentBean.setId("2376");
            contentBean.setName("西安市");
            contentBean.setFirstCharacter("X");
            contentBean.setCode("2376");
            List<RegionsBean.EmbeddedBean.ContentBean> list = new ArrayList<>();
            list.add(contentBean);
            embeddedBean.setContent(list);
            regionsBean.set_embedded(embeddedBean);
            return regionsBean;
        }
    }


    /**
     * 登录状态
     *
     * @param context
     * @return
     */
    public boolean getIsLogin(Context context) {
        return getBoolean(context, "islogin");
    }

    public void setIsLogin(Context context, boolean isLogin) {
        putBoolean(context, "islogin", isLogin);
    }

    /**
     * 是否绑定手机
     *
     * @param context
     * @return
     */
    public boolean getIsBindPhone(Context context) {
        return getBoolean(context, "isBindPhone");
    }

    public void setIsBindPhone(Context context, boolean isLogin) {
        putBoolean(context, "isBindPhone", isLogin);
    }

    /**
     * 签到状态
     *
     * @param context
     * @return
     */
    public boolean getIsSign(Context context) {
        return getBoolean(context, "isSign");
    }

    public void setIsSign(Context context, boolean isSign) {
        putBoolean(context, "isSign", isSign);
    }

    /**
     * 积分
     *
     * @param context
     * @return
     */
    public double getIntegralNum(Context context) {
        return getInt(context, "integralNum");
    }

    public void setIntegralNum(Context context, int integralNum) {
        putInt(context, "integralNum", integralNum);
    }

    /**
     * 登录方式类型
     *
     * @param context
     * @return
     */
    public int getLoginType(Context context) {
        return getInt(context, "loginType");
    }

    public void setLoginType(Context context, int loginType) {
        putInt(context, "loginType", loginType);
    }

    /**
     * 获取微信用户昵称
     *
     * @param context
     * @return
     */
    public String getNickname(Context context) {
        return getString(context, "wxNickName");
    }

    public void setNickname(Context context, String nickName) {
        putString(context, "wxNickName", nickName);
    }

    /**
     * 获取微信用户Uid
     *
     * @param context
     * @return
     */
    public String getWxUd(Context context) {
        return getString(context, "wxUid");
    }

    public void setWxUd(Context context, String nickName) {
        putString(context, "wxUid", nickName);
    }

    /**
     * 获取当前经度
     *
     * @param context
     * @return
     */
    public String getCurrentLon(Context context) {
        BaseCommLocateInfo baseCommLocateInfo = getCurrentCommuity(context);
        return baseCommLocateInfo.lon;
    }

    /**
     * 获取当前维度
     *
     * @param context
     * @return
     */
    public String getCurrentLat(Context context) {
        BaseCommLocateInfo baseCommLocateInfo = getCurrentCommuity(context);
        return baseCommLocateInfo.lat;
    }

    /**
     * 获取当前citycode
     *
     * @param context
     * @return
     */
    public String getCityCode(Context context) {
        BaseCommLocateInfo baseCommLocateInfo = getCurrentCommuity(context);
        return baseCommLocateInfo.citycode;
    }

    /**
     * 获取当前areaCode
     *
     * @param context
     * @return
     */
    public String getAreaCode(Context context) {
        BaseCommLocateInfo baseCommLocateInfo = getCurrentCommuity(context);
        return baseCommLocateInfo.areaCode;
    }

    /**
     * 用户userID
     *
     * @param context
     * @param userId
     */
    public void setUserId(Context context, String userId) {
        putString(context, "user_id", userId);
    }

    public long getUserId(Context context) {
        String userId = getString(context, "user_id");
        if (!Preconditions.isNullOrEmpty(userId)) {
            return Long.parseLong(userId);
        } else {
            return 0;
        }
    }

    public void setUserBaseInfo(Context context, LoginBaseInfo loginBaseInfo) {
        if (loginBaseInfo != null) {
            String jsonData = JSON.toJSONString(loginBaseInfo);
            putString(context, "login_base_info", jsonData);
        } else {
            putString(context, "login_base_info", "");
        }
    }

    public LoginBaseInfo getUserBaseInfo(Context context) {
        String jsonData = getString(context, "login_base_info");
        if (!Preconditions.isNullOrEmpty(jsonData)) {
            return JsonUtils.parseObject(jsonData, LoginBaseInfo.class);
        } else {
            return null;
        }
    }

    /**
     * 获取Session
     *
     * @param context
     * @return
     */
    public String getSession(Context context) {
        String jsonData = getString(context, "login_base_info");
        LoginBaseInfo loginBaseInfo = JsonUtils.parseObject(jsonData, LoginBaseInfo.class);
        if (!Preconditions.isNullOrEmpty(loginBaseInfo) && !Preconditions.isNullOrEmpty(loginBaseInfo.getSession())) {
            return loginBaseInfo.getSession();
        }
        return "";
    }

    /**
     * 获取卡包支付手机号
     *
     * @param context
     * @return
     */
    public String getCardPhone(Context context) {
        String access_Token = getString(context, "card_phone");
        return access_Token;
    }

    public void setCardPhone(Context context, String card_phone) {
        putString(context, "card_phone", card_phone);
    }

    /**
     * 获取Access_token
     *
     * @param context
     * @return
     */
    public String getAccess_token(Context context) {
        String access_Token = getString(context, "access_Token");
        return access_Token;
    }

    public void setAccessToken(Context context, String access_Token) {
        putString(context, "access_Token", access_Token);
    }

    /**
     * 获取refresh_token
     *
     * @param context
     * @return
     */
    public String getRefreshToken(Context context) {
        String refresh_Token = getString(context, "refresh_Token");
        return refresh_Token;
    }

    public void setRefreshToken(Context context, String access_Token) {
        putString(context, "refresh_Token", access_Token);
    }

    /**
     * 获取微信_token
     *
     * @param context
     * @return
     */
    public String getWeChatToken(Context context) {
        String access_Token = getString(context, "wxToken");
        return access_Token;
    }

    public void setWeChatToken(Context context, String access_Token) {
        putString(context, "wxToken", access_Token);
    }

    /**
     * 获取openid
     *
     * @param context
     * @return
     */
    public String getOpenid(Context context) {
        String access_Token = getString(context, "openid");
        return access_Token;
    }

    public void setOpenid(Context context, String openid) {
        putString(context, "openid", openid);
    }

    /**
     * 获取短信Code
     *
     * @param context
     * @return
     */
    public String getSmsCode(Context context) {
        String smsCode = getString(context, "sms_code");
        return smsCode;
    }

    public void setSmsCode(Context context, String openid) {
        putString(context, "sms_code", openid);
    }

    public void setNoticeStatus(Context context, int status) {
        putInt(context, "isNotice", status);
    }

    /**
     * 获取消息权限开启提示
     *
     * @param context
     * @return
     */
    public int getNoticeStatus(Context context) {
        int status = getInt(context, "isNotice");
        return status;

    }

    public void setCircleStatus(Context context, int status) {
        putInt(context, "hasCircle", status);
    }

    /**
     * 获取是否加入邻里圈的状态
     *
     * @param context
     * @return
     */
    public int getCircleStatus(Context context) {
        int status = getInt(context, "hasCircle");
        return status;

    }

    /**
     * 获取定位lat
     *
     * @param context
     * @return
     */
    public String getComLat(Context context) {
        String lat = getString(context, "com_lat");
        return lat;
    }

    public void setComLat(Context context, String lat) {
        putString(context, "com_lat", lat);
    }

    /**
     * 获取定位lon
     *
     * @param context
     * @return
     */
    public String getComLon(Context context) {
        String lon = getString(context, "com_lon");
        return lon;
    }

    public void setComLon(Context context, String lon) {
        putString(context, "com_lon", lon);
    }

    public void setObject(Context context, String key, Object obj) {
        try {
            // 保存对象
            SharedPreferences.Editor sharedata = context.getSharedPreferences(FILE_NAME, 0).edit();
            //先将序列化结果写到byte缓存中，其实就分配一个内存空间
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream os = new ObjectOutputStream(bos);
            //将对象序列化写入byte缓存
            os.writeObject(obj);
            //将序列化的数据转为16进制保存
            String bytesToHexString = bytesToHexString(bos.toByteArray());
            //保存该16进制数组
            sharedata.putString(key, bytesToHexString);
            sharedata.apply();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Object getObject(Context context, String key) {
        Object obj = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream is = null;
        try {
            if (contains(context, key)) {
                String string = getString(context, FILE_NAME, key);
                if (!TextUtils.isEmpty(string)) {
                    //将16进制的数据转为数组，准备反序列化
                    byte[] stringToBytes = StringToBytes(string);
                    bis = new ByteArrayInputStream(stringToBytes);
                    is = new ObjectInputStream(bis);
                    //返回反序列化得到的对象
                    obj = is.readObject();
                }
            }
        } catch (StreamCorruptedException e) {
            obj = null;
            e.printStackTrace();
        } catch (IOException e) {
            obj = null;
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            obj = null;
            e.printStackTrace();
        } finally {
            try {
                if (bis != null && is != null) {
                    bis.close();
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //所有异常返回null
        return obj;
    }
}
